package com.jimmy.proxy.jdkproxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @version 1.0
 * @ ClassName UserProxy
 * <p> TODO
 * @ author JIMMY
 * @ Date 2020/11/2 0002 下午 10:14
 */
public class UserProxy implements InvocationHandler {
    private UserService userService;

    /**
     * 返回接口
     * @param userService
     * @return
     */
    public UserService createProxy(UserService userService){
        this.userService = userService;
        //获取类加载器
        ClassLoader classLoader = userService.getClass().getClassLoader();
        //获取所有的实现类接口类型数组
        Class[] interfaces = userService.getClass().getInterfaces();
        return (UserService) Proxy.newProxyInstance(classLoader,interfaces,this);
    }

    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        if (method.getName().equals("save")){
            System.out.println("before");
        }
        //调用原始的操作,得到返回值
        Object object = method.invoke(userService);
        if (method.getName().equals("save")){
            System.out.println("after");
        }
        return object;
    }

    public static void main(String[] args) {
        //创建一个被代理对象
        UserServiceImpl userService = new UserServiceImpl();
        //使用代理得到一个代理对象
        UserService proxy = new UserProxy().createProxy(userService);
        proxy.save();
    }
}
